from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.contrib.auth import get_permission_codename
from django.contrib.admin.models import LogEntry

from badd.custom_site import custom_site
from badd.base_admin import BaseAdmin
from .models import Post, Category, Tag
from .adminforms import PostAdminForm


class PostInline(admin.TabularInline):  # StackedInline 样式
    fields = ('title', 'desc', 'owner')
    extra = 1   # 控制额外多几个
    model = Post

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not obj:
            # 设置默认值
            formset.form.base_fields['owner'].initial = request.user
        return formset


@admin.register(Category, site=custom_site)
class CategoryAdmin(BaseAdmin):
    inlines = [PostInline, ]

    list_display = ('name', 'status', 'is_nav', 'created_time', 'post_count')
    fields = ('name', 'status', 'is_nav')

    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super(CategoryAdmin, self).save_model(request, obj, form, change)

    def post_count(self, obj):
        return obj.post_set.count()

    post_count.short_description = '文章数量'


@admin.register(Tag, site=custom_site)
class TagAdmin(BaseAdmin):
    list_display = ('name', 'status', 'created_time')
    fields = ('name', 'status')

    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super(TagAdmin, self).save_model(request, obj, form, change)


class CategoryOwnerFilter(admin.SimpleListFilter):
    title = '分类过滤器'
    parameter_name = 'owner_category'

    def lookups(self, request, model_admin):
        return Category.objects.filter(owner=request.user).values_list('id', 'name')

    def queryset(self, request, queryset):
        category_id = self.value()
        if category_id:
            return queryset.filter(category_id=self.value())
        return queryset


@admin.register(Post, site=custom_site)
class PostAdmin(BaseAdmin):
    form = PostAdminForm
    list_display = [
        'title', 'category', 'status', 'created_time', 'owner', 'operator'
    ]

    list_display_links = []
    list_filter = [CategoryOwnerFilter]   # admin页面右侧的过滤
    # list_filter = ['category']   # admin页面右侧的过滤
    search_fields = ['title', 'category__name']

    actions_on_top = True
    # actions_on_bottom = True

    save_on_top = True

    # fields = (
    #     ('category', 'title'),
    #     'desc',
    #     'status',
    #     'content',
    #     'tag'
    # )
    fieldsets = (
        ('基础配置', {
            'description': '基础配置描述',
            'fields': (
                ('title', 'category'),
                'status',
            ),
        }),
        ('内容', {
            'fields': (
                'desc',
                'content'
            )
        }),
        ('额外信息', {
            'classes': ('wide',),
            'fields': ('tag', ),
        }),
    )
    # filter_horizontal = ('tag',)
    filter_vertical = ('tag', )

    def operator(self, obj):
        return format_html(
            '<a href="{}">edit</a>',
            reverse('cus_admin:blog_post_change', args=(obj.id,))
        )

    operator.short_description = 'Operation'

    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super(PostAdmin, self).save_model(request, obj, form, change)

    def get_queryset(self, request):
        qs = super(PostAdmin, self).get_queryset(request)
        return qs.filter(owner=request.user)

    class Media:
        css = {
            'all': ('',)
        }
        js = (
            '',
        )

    # 权限相关四个接口 has_add_permission has_change_permission has_delete_permission has_module_permission
    def has_add_permission(self, request):
        opts = self.opts
        codename = get_permission_codename('add', opts)
        perm_code = "%s.%s" % (opts.app_label, codename)
        # 通过perm code 去公司系统查询是否有权限
        # PERMISSION_API = 'https://sso.xx?username={}coded={}'
        PERMISSION_API = ''
        resp = request.get(PERMISSION_API, format(request.user.username, perm_code)) if PERMISSION_API else True
        return True

    def has_change_permission(self, request, obj=None):
        return super(PostAdmin, self).has_change_permission(request, obj)

    def has_delete_permission(self, request, obj=None):
        return super(PostAdmin, self).has_delete_permission(request, obj)

    def has_module_permission(self, request):
        return super(PostAdmin, self).has_module_permission(request)


@admin.register(LogEntry, site=custom_site)
class LogEntryAdmin(admin.ModelAdmin):
    list_display = ['object_repr', 'object_id', 'action_flag', 'user', 'change_message']
